package com.lwj.liwanjia.view.fragment.myindent;


import android.content.Intent;
import android.net.Uri;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.baoyz.widget.PullRefreshLayout;
import com.lwj.liwanjia.R;
import com.lwj.liwanjia.adapter.indent.AllAdapter;
import com.lwj.liwanjia.base.LazyFragment;
import com.lwj.liwanjia.bean.CancleIndentBean;
import com.lwj.liwanjia.bean.DeleteIndentBean;
import com.lwj.liwanjia.bean.DeleteUnpaidBean;
import com.lwj.liwanjia.config.OnClickPosition;
import com.lwj.liwanjia.impl.DeleteIndentView;
import com.lwj.liwanjia.bean.MyIndentBean;
import com.lwj.liwanjia.bean.QuerenBean;
import com.lwj.liwanjia.config.OnItemChildClickListener;
import com.lwj.liwanjia.config.OnItemClickListener;
import com.lwj.liwanjia.impl.CancleIndentView;
import com.lwj.liwanjia.impl.DeleteUnpaidView;
import com.lwj.liwanjia.impl.MyIndentView;
import com.lwj.liwanjia.impl.QuerenView;
import com.lwj.liwanjia.presenter.CancleIndentPresenter;
import com.lwj.liwanjia.presenter.DeleteIndentPresenter;
import com.lwj.liwanjia.presenter.DeleteUnpaidPresenter;
import com.lwj.liwanjia.presenter.MyIndentPresenter;
import com.lwj.liwanjia.presenter.QuerenIndentPresenter;
import com.lwj.liwanjia.utils.CancleDialog;
import com.lwj.liwanjia.utils.SpfUtils;
import com.lwj.liwanjia.view.activity.indent.UnpaidActivity;
import com.lwj.liwanjia.view.activity.myindent.ShangChengPjActivity;
import com.lwj.liwanjia.view.activity.myindent.ZhuijiaPjActivity;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 全部
 */
public class AllIndentFragment extends LazyFragment implements MyIndentView, DeleteIndentView, DeleteUnpaidView, QuerenView, CancleIndentView, PullRefreshLayout.OnRefreshListener {
    @BindView(R.id.all_rlv)
    RecyclerView allRlv;
    @BindView(R.id.progress)
    ProgressBar progressBar;
    @BindView(R.id.no_indent)
    TextView noIndent;
    @BindView(R.id.refressh)
    PullRefreshLayout refreshLayout;

    private int deletePostition = 0;//删除的位置
    // 标志位，标志已经初始化完成。
    private boolean isPrepared;
    //    private List<AllIndentBean> beanList = new ArrayList<>();//测试数据
    private List<MyIndentBean.DataBean> beanList = new ArrayList<>();
    private AllAdapter allAdapter;
    private MyIndentPresenter myIndentPresenter;//所有订单
    private QuerenIndentPresenter querenIndentPresenter;//确认收货
    private DeleteIndentPresenter deleteIndentPresenter;//删除订单
    private String token;
    private int circleType = 0;//判断是否是刷新中0
    private CancleIndentPresenter canclePresenter;//待发货取消订单
    private CancleDialog dialog;//待付款,待发货，删除订单,申请退款
    private DeleteUnpaidPresenter deleteUnpaidPresenter;//删除待付款时间到了的订单

    @Override
    protected void lazyLoad() {
        if (!isPrepared || !isVisible) {
            return;
        }
        initData();
    }

    private void initData() {
        myIndentPresenter.getIndentData(token, "全部");
    }

    @Override
    protected void initView() {
        final LinearLayoutManager manager = new LinearLayoutManager(getActivity());
        manager.setOrientation(LinearLayoutManager.VERTICAL);
        allRlv.setLayoutManager(manager);
        allAdapter = new AllAdapter(getActivity(), beanList, false);
        allRlv.setAdapter(allAdapter);
        refreshLayout.setOnRefreshListener(this);
        myIndentPresenter = new MyIndentPresenter(this);
        deleteIndentPresenter = new DeleteIndentPresenter(this);
        querenIndentPresenter = new QuerenIndentPresenter(this);
        canclePresenter = new CancleIndentPresenter(this);
        deleteUnpaidPresenter = new DeleteUnpaidPresenter(this);
        token = SpfUtils.getSpfUtils(getActivity()).getToken();
        listener();
        isPrepared = true;
        lazyLoad();
    }

    private void listener() {
        //记录点击的位置
        allAdapter.setClickPosition(new OnClickPosition() {
            @Override
            public void clickPosition(int position) {
                deletePostition = position;
            }
        });
        allAdapter.setListener(new OnItemClickListener() {
            @Override
            public void OnItemClick(View view, int position) {
                deletePostition = position;
                Intent intent = new Intent(getActivity(), UnpaidActivity.class);
                intent.putExtra("tradeId", beanList.get(position).getGoods().getTradeId());
                startActivity(intent);
            }
        });
        allAdapter.setChildListener(new OnItemChildClickListener() {
            @Override
            public void OnItemChildClick(View view, String status, final int position) {
                deletePostition = position;
                TextView tv = (TextView) view;
                if (status.equals("订单取消")) {
                    switch (tv.getText().toString()) {
                        case "删除订单":
                            dialog = new CancleDialog(getActivity(), beanList.get(position).getGoods().getStatus());
                            dialog.show();
                            dialog.getSure().setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    deleteUnpaidPresenter.deleteUnpaidIndent(token, beanList.get(position).getGoods().getTradeId());
                                    dialog.dismiss();
                                }
                            });
                            break;
                    }
                } else if (status.equals("待发货")) {
                    switch (tv.getText().toString()) {
                        case "取消订单":
                            dialog = new CancleDialog(getActivity(), beanList.get(position).getGoods().getStatus());
                            dialog.show();
                            dialog.getSure().setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    canclePresenter.CancleIndent(token, beanList.get(position).getGoods().getTradeId());
                                    dialog.dismiss();
                                }
                            });
                            break;
                        case "联系商家":
                            Intent intent = new Intent();
                            intent.setAction(Intent.ACTION_DIAL);
                            intent.setData(Uri.parse("tel:" + beanList.get(position).getGoods().getShoptel()));
                            startActivity(intent);
                            break;
                    }
                } else if (status.equals("待收货")) {
                    switch (tv.getText().toString()) {
                        case "联系商家":
                            Intent intent = new Intent();
                            intent.setAction(Intent.ACTION_DIAL);
                            intent.setData(Uri.parse("tel:" + beanList.get(position).getGoods().getShoptel()));
                            startActivity(intent);
                            break;
                        case "确认收货":
                            querenIndentPresenter.querenIndent(token, beanList.get(position).getGoods().getTradeId());
                            break;
                    }
                } else if (status.equals("已完成")) {
                    switch (tv.getText().toString()) {
                        case "删除订单":
                            dialog = new CancleDialog(getActivity(), beanList.get(position).getGoods().getStatus());
                            dialog.show();
                            dialog.getSure().setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    deleteIndentPresenter.deleteIndent(token, beanList.get(position).getGoods().getTradeId());
                                    dialog.dismiss();
                                }
                            });
                            break;
                        case "评价":
                            Intent intent1 = new Intent(getActivity(), ShangChengPjActivity.class);
                            intent1.putExtra("infor", beanList.get(position).getGoods());
                            startActivity(intent1);
                            break;
                        case "追加评价":
                            Intent intent2 = new Intent(getActivity(), ZhuijiaPjActivity.class);
                            intent2.putExtra("infor", beanList.get(position).getGoods());
                            startActivity(intent2);
                            break;
                        case "联系商家":
                            Intent intent = new Intent();
                            intent.setAction(Intent.ACTION_DIAL);
                            intent.setData(Uri.parse("tel:" + beanList.get(position).getGoods().getShoptel()));
                            startActivity(intent);
                            break;
//                        case "在线沟通":
//                        startActivity(new Intent(getActivity(), KefuActivity.class));
//                        break;
                    }
                } else {//未同意退货、退款订单
                    switch (tv.getText().toString()) {
                        case "删除订单":
                            dialog = new CancleDialog(getActivity(), beanList.get(position).getGoods().getStatus());
                            dialog.show();
                            dialog.getSure().setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    deleteIndentPresenter.deleteIndent(token, beanList.get(position).getGoods().getTradeId());
                                    dialog.dismiss();
                                }
                            });
                            break;
                        case "联系商家":
                            Intent intent = new Intent();
                            intent.setAction(Intent.ACTION_DIAL);
                            intent.setData(Uri.parse("tel:" + beanList.get(position).getGoods().getShoptel()));
                            startActivity(intent);
                            break;
                    }
                }
            }

        });
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_all_indent;
    }

    @Override
    public void showProgress() {
        if (circleType == 0) {
            progressBar.setVisibility(View.VISIBLE);
        }
    }

    @Override
    public void hideProgress() {
        progressBar.setVisibility(View.GONE);
    }

    @Override
    public void showError(Exception e) {
        Toast.makeText(getActivity(), "数据加载失败", Toast.LENGTH_SHORT).show();
        refreshLayout.setRefreshing(false);
    }

    /**
     * 删除付款时间已经到了的订单
     *
     * @param deleteUnpaidBean
     */
    @Override
    public void deleteUnpaidIndent(DeleteUnpaidBean deleteUnpaidBean) {
        if (deleteUnpaidBean.getState() == 0) {
            Toast.makeText(getActivity(), "删除失败", Toast.LENGTH_SHORT).show();
        } else if (deleteUnpaidBean.getState() == 1) {
            if (deleteUnpaidBean.getData().getStatus().equals("删除成功")) {
                Toast.makeText(getActivity(), "删除成功", Toast.LENGTH_SHORT).show();
                beanList.remove(deletePostition);
                if (beanList.size() == 0) {
                    allRlv.setVisibility(View.GONE);
                    noIndent.setVisibility(View.VISIBLE);
                }
                allAdapter.notifyDataSetChanged();
            }
        }
    }

    /**
     * 待发货申请退款（商城和超市）
     *
     * @param cancleIndentBean
     */
    @Override
    public void cancleIndent(CancleIndentBean cancleIndentBean) {
        if (cancleIndentBean.getState() == 0) {
            Toast.makeText(getActivity(), "申请失败", Toast.LENGTH_SHORT).show();
        } else if (cancleIndentBean.getState() == 1) {
            if (cancleIndentBean.getData().getStatus().equals("退款申请")) {
                Toast.makeText(getActivity(), "退款申请成功", Toast.LENGTH_SHORT).show();
                beanList.remove(deletePostition);
                if (beanList.size() == 0) {
                    allRlv.setVisibility(View.GONE);
                    noIndent.setVisibility(View.VISIBLE);
                }
                allAdapter.notifyDataSetChanged();
            }
        }
    }

    /**
     * 确认收货（商城和超市）
     *
     * @param querenBean
     */
    @Override
    public void querenIndent(QuerenBean querenBean) {
        if (querenBean.getState() == 1) {
            if (querenBean.getData().getStatus().equals("订单完成")) {
                beanList.get(deletePostition).getGoods().setStatus("已完成");
                allAdapter.notifyDataSetChanged();
            } else {
                Toast.makeText(getActivity(), "确认收货失败", Toast.LENGTH_SHORT).show();
            }
        } else {
            Toast.makeText(getActivity(), "访问失败", Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 获取所有订单
     *
     * @param myIndentBean
     */
    @Override
    public void getIndentData(MyIndentBean myIndentBean) {
        if (myIndentBean.getState() == 0) {
            Toast.makeText(getActivity(), "访问有误", Toast.LENGTH_SHORT).show();
        } else {
            beanList.clear();
            beanList.addAll(myIndentBean.getData());
            if (beanList.size() > 0) {
                noIndent.setVisibility(View.GONE);
                allRlv.setVisibility(View.VISIBLE);
                allAdapter.notifyDataSetChanged();
            } else {
                noIndent.setVisibility(View.VISIBLE);
                allRlv.setVisibility(View.GONE);
            }
        }
        allRlv.scrollToPosition(deletePostition);
        circleType = 0;
        refreshLayout.setRefreshing(false);
    }

    @OnClick(R.id.no_indent)
    public void onViewClicked() {
        initData();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        allAdapter.cancelAllTimers();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (myIndentPresenter != null) {
            myIndentPresenter = null;
        }
    }

    /**
     * 删除订单
     *
     * @param deleteBean
     */
    @Override
    public void deleteIndent(DeleteIndentBean deleteBean) {
        if (deleteBean.getState() == 0) {
            Toast.makeText(getActivity(), "访问有误", Toast.LENGTH_SHORT).show();
        } else {
            if (deleteBean.getData().getStatus().equals("删除成功")) {
                beanList.remove(deletePostition);
                if (beanList.size() == 0) {
                    allRlv.setVisibility(View.GONE);
                    noIndent.setVisibility(View.VISIBLE);
                }
                allAdapter.notifyDataSetChanged();
            } else {
                Toast.makeText(getActivity(), "删除失败", Toast.LENGTH_SHORT).show();
            }
        }
    }

    @Override
    public void onRefresh() {
        circleType = 1;
        initData();
    }

    @Override
    public void onResume() {
        super.onResume();
        if (isPrepared && isVisible) {//当页面是可见，且都已经布局好了时才访问数据
            initData();
        }
    }
}
